import { ABORT_PROGRAM, OPERATION_PAUSE_PROGRAM, OPERATION_RESUME_PROGRAM } from '@/constants/Command'
import type { ApplianceBrand } from '@/types/appliance'
import type { WS } from '@/utils/socket/types'
import { GetRequest, PostRequest, PutRequest, DeleteRequest } from '@/utils/request'
import type { submitDataType, submitSettingType } from '@/pages/appliance/BIWD/favoriteList/favoriteList.vue'
import type { FavoriteProgramsValueType } from '@/pages/appliance/Dishwasher/editFavoriteProgram/editFavoriteProgram.vue'
import type { TTRoomValueType } from '@/pages/appliance/TT/TTHelper'
import netconfig from '@/config/netconfig'
import type { PairTemplateContent } from './content'

export type ApplianceInfo = {
  brand: string
  cdate: string
  connected: boolean
  displayTimes: {
    remainingProgramTime: number | null
    finishInAbsolute: string | null
    startInAbsolute: string | null
  } | null
  displayValue: string | null
  haId: string
  name: string
  operationState: string | null
  picture: string
  powerState: string | null
  type: string
  vib: string
  is_virtual_appliance: boolean
}

/**
 * 获取家电详情接口
 */
export function getHomeAppliances() {
  return GetRequest<ApplianceInfo[] | null>(`/api/HA/homeappliances`)
}
export namespace ApplianceProgram {
  export type Group = {
    key: string
    name: string
    programs: ApplianceProgram.Scope[]
  }
  export type Scope = {
    key: string
    name: string
    mediumDescription: string
    constraints: {
      execution: string
    }
    trackName?: string
    baseProgramKey?: string
  }
  export type BaseOption = {
    type: 'Enum' | 'Integer' | string
    key: string
    name: string
    description: string
    param: string
    default?: number
    unit?: string
  }
  export type IntegerOption = BaseOption & {
    type: 'Integer'
    min: number
    max: number
    step?: number
  }
  export type EnumOption = BaseOption & {
    type: 'Enum'
    enumValues?: {
      value: string
      displayValue: string
    }[]
  }
  export type Option = IntegerOption | EnumOption

  /**
   * 自定义程序类型
   */
  export type LocalProgramType = ApplianceProgram.Scope & {
    isLocalLeft: boolean
    isLocalRight: boolean
    isNullProgram: boolean
  }
}

/**
 * 获取家电程序列表
 */
export function getApplianceProgramList(haId: string) {
  return GetRequest<{ programs: ApplianceProgram.Scope[] }>(`/api/HA/${haId}/scope`)
}

export type HistoryProgram = {
  key: string
  name: string
  programType: HistoryProgramTypes
  serverTime: string
  options: HistoryProgramOption[]
  duration: number
}
export enum HistoryProgramTypes {
  StartedProgram = 0,
  OrderedProgram = 1,
}
export type HistoryProgramOption = {
  key: string
  name: string
  value: string | number | boolean
  displayvalue: string | null
  unit?: string
}
/**
 * 获取家电程序最近启动预约列表
 */
export function getApplianceHistoryProgramList(haId: string) {
  return GetRequest<HistoryProgram[]>(`/api/HA/${haId}/activeHistory`)
}

export namespace ProgramAvailable {
  export type Scope = {
    key: string
    name: string
    options?: ProgramAvailable.Option[]
    mediumDescription?: string
  }
  export type Option = IntegerOption | DoubleOption | BooleanOption | EnumOption | BaseOption
  type BaseOption = {
    key: string
    type: string
    name?: string
    unit?: string
    constraints?: {}
    displayvalue?: string
    value?: string
  }
  type BaseNumberOption = BaseOption & {
    unit: string
    constraints: {
      max: number
      min: number
      default?: number
      stepsize?: number
    }
  }
  export type IntegerOption = BaseNumberOption & {
    type: 'Int'
  }
  export type DoubleOption = BaseNumberOption & {
    type: 'Double'
  }
  export type NumberOption = IntegerOption | DoubleOption
  export type BooleanOption = BaseOption & {
    type: 'Boolean'
    constraints: {
      default: boolean
      liveupdate: boolean
    }
  }
  export type EnumOption = BaseOption & {
    type: string
    constraints: {
      allowedvalues: string[] // 枚举值
      displayvalues: string[] // 枚举显示文本
      liveupdate: boolean
    }
  }
  // 仅Demo Mode存在此类型
  export type DemoEstimatedOption = {
    key: 'BSH.Common.Option.EstimatedTotalProgramTime'
    value: number
    unit: 'seconds'
    name: string
  }
}
/**
 * 获取家电程序扩展参数
 */
export function getProgramAvailableScope(haId: string, programKey: string) {
  return GetRequest<ProgramAvailable.Scope>(`/api/HA/${haId}/available/${programKey}`)
}

export type ApplianceSetting = {
  [x: string]: any
  key: string
  value?: string | boolean | number | FavoriteProgramsValueType[] | TTRoomValueType[]
  name?: string
  displayvalue?: string | number
  unit?: string
  type?: string
  constraints?: ApplianceSettingConstraints
}
export type ApplianceSettingConstraints = {
  allowedvalues?: string[]
  displayvalues?: string[]
  access?: string
  max?: number
  min?: number
  stepsize?: number
  extrovalue?: {
    displayvalue: string
    allowedvalue: string
  }
}
/**
 * 获取全部家电设置的接口
 */
export type ApplianceSettingDes = ApplianceSetting & {
  mediumDescription?: string
}
export function getAllSetting(haId: string, ignoreErrorTips?: boolean) {
  return GetRequest<{ settings: ApplianceSettingDes[] }>(`/api/HA/${haId}/settings`, void 0, { ignoreErrorTips })
}

export type ApplianceSimpleSetting = {
  default?: string
  param?: string
  name: string
  type?: string
  key: string
  value?: number
  enumValues?: ApplianceSimpleSettingEnumValues[]
  min?: string
  max?: string
  en?: string | null
  zh?: string | null
  step?: string
}
export type ApplianceSimpleSettingEnumValues = {
  machineValue: string
  en: string
  bshValue: string
  zh: string | null
}
export function getSimpleSetting(haId: string) {
  return GetRequest<{ settings: ApplianceSimpleSetting[] }>(`/api/homeappliances/${haId}/blSimpleSettings`)
}

export function getSetting(haId: string, key: string) {
  return GetRequest<ApplianceSetting>(`/api/HA/${haId}/settings/${key}`)
}

export function setSetting(
  haId: string,
  key: string,
  value: string | boolean | number | object,
  options?: { ignoreError?: boolean; others?: Record<string, any> }
) {
  return PutRequest<null>(
    `/api/homeappliances/v1/${haId}/settings/${key}`,
    { data: { key, value, ...options?.others } },
    { ignoreErrorTips: options?.ignoreError }
  )
}

export function setSettingBySettings(haId: string, key: string, value: string | boolean | number | object) {
  return PutRequest<null>(`/api/homeappliances/v1/${haId}/settings/${key}`, { data: { settings: [{ key, value }] } })
}
export function setSettingByNokeySettings(haId: string, key: string, value: string | boolean | number | object) {
  return PutRequest<null>(`/api/homeappliances/v1/${haId}/settings`, { data: { settings: [{ key, value }] } })
}
export function setSettingByNokeySettingsGroup(haId: string, data: ApplianceCommandGroup[]) {
  return PutRequest<null>(`/api/homeappliances/v1/${haId}/settings`, { data: { settings: data } })
}
export type ApplianceCommand = {
  key: string
  name?: string
}
export type ApplianceCommandGroup = {
  key: string
  value: string
}
/**
 * 获取家电当前支持commands
 */
export function getAppSupportCommands(haId: string, options?: { ignoreError?: boolean }) {
  return GetRequest<{ commands: ApplianceCommand[] }>(`/api/homeappliances/v1/${haId}/commands`, void 0, {
    ignoreErrorTips: options?.ignoreError,
  })
}

export function setCommand<ValueType>(
  haId: string,
  key: string,
  value: ValueType,
  options?: { ignoreError?: boolean }
) {
  return PutRequest<null>(
    `/api/homeappliances/v1/${haId}/commands/${key}`,
    { data: { key, value } },
    {
      ignoreErrorTips: options?.ignoreError,
    }
  )
}

export type ApplianceStatus = {
  key: string
  value: string | number | boolean
  name?: string
  displayvalue?: string
}
/**
 * 单个status接口
 */
export function getStatusKey(haId: string, key: string) {
  return GetRequest<ApplianceStatus>(`/api/homeappliances/${haId}/status/${key}`)
}

/**
 * status接口
 */
export function getStatus(haId: string) {
  return GetRequest<{ status: ApplianceStatus[] }>(`/api/homeappliances/${haId}/status`)
}

/**
 * 获取家电事件
 */
export function getEvents(haId: string, options?: { ignoreError?: boolean }) {
  return GetRequest<{ events: WS.MessageItem[] }>(`/api/homeappliances/${haId}/events`, void 0, {
    ignoreErrorTips: options?.ignoreError,
  })
}

export type VibInfo = {
  appearChar: number
  brand: ApplianceBrand
  catelog: string
  catelog_name: string
  catelog_pic: string
  deviceSubType: string
  launched: number
  photo: string
  pic: string
  type: string
  vibLabel: { id: number; label: string }[]
}
export function getVibInfo(vib: string) {
  return PostRequest<VibInfo>(`/api/installguide/v1/pairing/simple/${vib}`)
}

export type ShareGuestHistory = {
  acceptTime: string
  guestId: string
  haName: string
  haid: string
  icon: string
  ownerId: string
  status: string
  tname: null
}
export type ShareHistoryShare = {
  acceptTime: string
  guestId: string
  haName: string
  haid: string
  icon: string
  ownerId: string
  status: string
  tname: string
}
export type ShareHistory = {
  guest: ShareGuestHistory[]
  loginId: string
  share: ShareHistoryShare[]
}

/**
 * 获取（三个月内）用户分享HA记录
 */
export function getSharingHistory() {
  return GetRequest<ShareHistory>(`/api/wx/share/homeAppliance/v1/history`)
}

/**
 * 获取家电详情
 */
export type ApplianceDetail = ApplianceInfo & {
  option: ApplianceDetailOption[] | null
  programKey: string | null
  programName: string | null
  ssid?: string | null
  znumber?: number | null
  storageActiveTime?: number
  enumber: string
  fd: string
  installable: boolean
  usageReport: boolean
  guest: boolean
  photo: string
  serialnumber?: string
  zn: string
  zh: string
  vibLabel?: { id: number; label: string }[]
  deviceSubType?: string
}
export type ApplianceDetailOption = {
  key: string
  value: string | number | boolean
  name?: string
  label?: string
  unit?: string
  displayvalue?: string
}
export function getApplianceDetail(haId: string) {
  return GetRequest<ApplianceDetail>(`/api/HA/homeappliances/${haId}`)
}

/**
 * 获取分享token
 */
export type ShareTokenType = {
  sharetoken: string
}
export function getSharing(haId: string, type: string) {
  return PostRequest<ShareTokenType>(`/api/wx/share/homeAppliance/v1/sharingtoken/${haId}`, { type })
}

/**
 * 删除控制
 */

export function removeShareApp(haId: string, guestId: string) {
  return PostRequest(`/api/wx/share/homeAppliance/v1/deregister/${haId}`, { guestId })
}

export type ProgramSelectedScope = {
  key: string
  name: string
  constraints: { access: string }
  options: ProgramSelectOption[]
}
export type ProgramSelectOption = {
  key: string
  name?: string
  value: string | number | boolean
  unit?: string
  displayvalue?: string
}
/**
 * 获取家电程序选中选项
 */
export function getProgramSelectedOptions(haId: string) {
  return GetRequest<ProgramSelectedScope>(`/api/homeappliances/v1/${haId}/programs/selected`)
}

/**
 * 选择程序
 */
export function selectProgram(haId: string, programKey: string, programOptions?: ProgramSelectOption[]) {
  return PutRequest<null>(`/api/homeappliances/v1/${haId}/programs/selected`, {
    data: { key: programKey, options: programOptions },
  })
}

/**
 * 调节程序参数
 */
export function adjustProgramOptions(haId: string, programOptions: ProgramSelectOption[]) {
  return PutRequest<null>(`/api/homeappliances/${haId}/programs/active/options`, { data: { options: programOptions } })
}

/**
 * 预约启动
 */
export function orderNow(
  haId: string,
  program: ApplianceProgram.Scope | HistoryProgram,
  options: ProgramSelectOption[] | HistoryProgramOption[]
) {
  return PutRequest<null>(`/api/homeappliances/v1/${haId}/programs/active`, {
    data: {
      key: program.key,
      options,
    },
  })
}

/**
 * 立即启动
 */
export function startNow(
  haId: string,
  program: ApplianceProgram.Scope | HistoryProgram,
  options: ProgramSelectOption[] | HistoryProgramOption[] = []
) {
  return PutRequest<null>(`/api/homeappliances/v1/${haId}/programs/active`, {
    data: {
      key: program.key,
      name: program.name,
      options: options || [],
      type: 1,
    },
  })
}

/**
 * 终止程序
 */
export function abortProgram(haId: string) {
  return setCommand(haId, ABORT_PROGRAM, true)
}

/**
 * 暂停程序
 */
export function pauseProgram(haId: string) {
  return setCommand(haId, OPERATION_PAUSE_PROGRAM, true)
}

/**
 * 继续程序
 */
export function resumeProgram(haId: string) {
  return setCommand(haId, OPERATION_RESUME_PROGRAM, true)
}

/**
 * 获取家电运行状态
 */
export function getOperationState(haId: string) {
  return GetRequest<ApplianceSetting>(`/api/homeappliances/${haId}/status/BSH.Common.Status.OperationState`)
}

/**
 * 获取家电Features (用于查询缓存状态)
 */
export type ApplianceFeatures = {
  commands: ApplianceCommand[]
  events: WS.MessageItem[]
  options: ProgramAvailable.Option[]
  programs: ApplianceProgram.Scope[]
  settings: ApplianceSetting[]
  status: ApplianceStatus[]
}
export function getFeatures(haId: string) {
  return GetRequest<ApplianceFeatures>(`/api/HA/${haId}/features`)
}

/**
 * 获取家电程序列表Features (用于查询缓存状态)
 */
export type ApplianceProgramFeatures = {
  programs: ApplianceProgram.Scope[]
}
export function getProgramFeatures(haId: string) {
  return GetRequest<ApplianceProgramFeatures>(`/api/HA/${haId}/features/programs`)
}

/**
 * 获取家电运行状态
 */
export type DishwasherDownPrograms = {
  downloadVib: string
  featureKey: string
  name: string
  paymentRequired: number
  sourceId: string
  status: number
  title: string
}
export function getDownloadablePrograms(haId: string) {
  return GetRequest<DishwasherDownPrograms[]>(`/api/homeappliances/installableContent/${haId}`)
}

/**
 * 获取家电可下载列表详情数据
 */
export type DishwasherDownProgramsDetail = {
  brand: string
  code: string
  detailPageUrl: string
  medias: {
    standardImage: {
      defaultUrl: string
    }
  }
  name: string
  paymentRequired: number
  shortDescription: {
    items: []
    title: [string]
  }
  status: number
}
export function getDownloadableProgramsDetail(haId: string, programKey: string) {
  return GetRequest<DishwasherDownProgramsDetail>(`/api/homeappliances/${haId}/productInformation/${programKey}`)
}

/**
 * 获取家电可下载列表技术数据
 */
export type ProgramMetadata = {
  featureKey: string
  metadata: {
    data: Record<string, number>
  }
}
export function getProgramMetadata(
  haId: string,
  programKey: string,
  payload: { parameters: { key: string; value: string | number | boolean | null }[]; useDefaultSettings: boolean }
) {
  return PostRequest<{ data: ProgramMetadata }>(`/api/homeappliances/${haId}/programMetadata/${programKey}`, payload)
}

export type GuestData = {}
export function getGuest(haId: string) {
  return GetRequest<{ guests: GuestData[] }>(`/api/wx/share/homeAppliance/guests/${haId}`)
}

/**
 * 删除家电
 * @param haId
 * @returns
 */
export function deregister(haId: string) {
  return PutRequest(`/api/v1/wx/v1/deregisterHomeAppliance/${haId}`)
}

/**
 * 修改家电名称
 */
export function changeApplianceName(haId: string, name: string) {
  return PostRequest(
    `/api/homeappliances/v1/${haId}/rename`,
    {
      name,
    },
    {
      ignoreErrorTips: true,
    }
  )
}

/**
 * 下载程序
 */
export function downloadProgram(haId: string, sourceId: string) {
  return PostRequest(`/api/wx/recipes/hacontents/${haId}/installed`, [{ contentSourceID: sourceId }])
}

/**
 * 删除下载程序
 */
export function delDownloadProgram(haId: string, sourceId: string) {
  return DeleteRequest(`/api/wx/recipes/hacontents/${haId}/installed/${sourceId}`)
}

/**
 * 查询下载进度
 */
export type SingleProgramsAddEdType = {
  installationState: string
}
export function getSingleProgramsAddEd(haId: string, sourceId: string) {
  return GetRequest<SingleProgramsAddEdType>(`/api/wx/recipes/hacontents/${haId}/installed/${sourceId}`)
}

/**
 * 查询下载进度
 */
export function installableContentInfo(haId: string) {
  return GetRequest<boolean>(`/api/homeappliances/installableContentInfo/${haId}`)
}

/**
 * 获取模糊搜索vib号
 */
export function getFuzzySearchData(key: string, displayed: number) {
  return GetRequest<string[]>(
    `/bshrecipes/recipes/mini/pairingguide/participlesearch?key=${key}&displayed=${displayed}`
  )
}

/**
 * 获取BIWD收藏程序列表
 */
export type FavouriteListType = {
  fav_pic: string
  fav_temp: string
  fav_vol: string
  name: string
}
export function getBIWDFavouriteList(haId: string) {
  return PostRequest<{ data: FavouriteListType[] }>(`/api/homeappliances/getFavouriteList/${haId}`)
}

/**
 * 新profile-切换家电程序
 */
export function setHomeAppliancePrograms(haId: string, payload: submitDataType) {
  return PostRequest(`/hcaextension/hcmini/v1/center/openControlNew/programs/${haId}`, { payload })
}

/**
 * 新profile-设置家电状态
 */
export function setHomeApplianceSettings(haId: string, settings: submitSettingType[]) {
  return PutRequest(`/api/homeappliances/v1/${haId}/settings`, { data: { settings: settings } })
}

/**
 * 新profile-设置家电状态
 */
export function setHVNHomeApplianceSettings(haId: string, key: string, settings: submitSettingType[]) {
  return PutRequest(`/api/homeappliances/v1/${haId}/settings/${key}`, { data: { settings: settings } })
}

type LocalMode = {
  id: number | string
  temperature: number
  modelName: string
  active: boolean
  description: string
}
/**
 * 获取变温冰箱活动信息
 */
export function getFlexModeSetting(haId: string) {
  return GetRequest<LocalMode>(`/api/WxuserHaidInfo/temperatureSetting/${haId}`)
}

/**
 * 获取家电设置settingGroup
 */
export type SettingGroupDataType = {
  settingsGroup: string
  settings: {
    homeApplianceTypes: string[]
    key: string
  }[]
}[]
export function getSettingGroups(type: string) {
  return GetRequest<SettingGroupDataType>(`/api/content/iotplatform/settingsgroup/${type}`)
}

export type RemoteControlGuideContent = PairTemplateContent
export function getRemoteControlGuide(vib: string) {
  return PostRequest<RemoteControlGuideContent>(`/api/installguide/v1/pairing/vibToTemplate/${vib}`, {
    chapterGroup: [6],
    hasShowAll: netconfig.isTester,
  })
}
